package com.iscreen.core.utils.jms;

import java.io.Serializable;

import javax.annotation.Resource;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import com.iscreen.core.services.flow.FlowMessage;
import com.iscreen.core.services.flow.FlowService;
import com.iscreen.core.services.flow.FlowType;
import com.iscreen.core.services.flow.StepType;
import com.iscreen.utils.exceptions.IScreenException;

public abstract class BaseMDB implements MessageListener
{
	@Resource
	protected MessageDrivenContext mdc;

	protected abstract Object processMessage(Serializable message) throws IScreenException;
	
	@Override
	public void onMessage(Message message)
	{
		try
		{
			Serializable msg = ((ObjectMessage) message).getObject();

			Serializable content = getMessageContent(msg);
			
			Object result = processMessage(content);

			if (isFlowMessage(msg))
			{
				completeStep(msg, result);
			}
		}
		catch (IScreenException e)
		{
			e.printStackTrace();
		}
		catch (JMSException e)
		{
			e.printStackTrace();
		}
	}

	private void completeStep(Serializable msg, Object result)
			throws IScreenException
	{
		FlowMessage flowMsg = (FlowMessage) msg;
		FlowType flowType = flowMsg.getFlowType();
		StepType currentStep = flowMsg.getStep();
		FlowService.getInstance().completeStep(flowType, currentStep, result);
	}

	private Serializable getMessageContent(Serializable msg)
	{
		Serializable content = msg;
		
		if (isFlowMessage(msg))
		{
			content = (Serializable) ((FlowMessage) msg).getMessage();
		}
		return content;
	}

	private boolean isFlowMessage(Serializable msg)
	{
		return msg instanceof FlowMessage;
	}
		
}
